package shopBean.common.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import javax.servlet.http.HttpServletRequest;

public class Tool {



	public static String getIpAddr(HttpServletRequest request) {
		String ipAddress = request.getHeader("x-forwarded-for");
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
			if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
				// 根据网卡取本机配置的IP
				java.net.InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				ipAddress = inet.getHostAddress();
			}
		}
		// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length() = 15
			if (ipAddress.indexOf(",") > 0) {
				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
		}
		return ipAddress;
	}

	/**
	 * 等级评分转换
	 * 
	 * @param level
	 *            等级
	 * @return 对应评分
	 */
	public static BigDecimal LevelConvert(Integer level) {
		switch (level) {
		case 1:
			return new BigDecimal(-1);
		case 2:
			return new BigDecimal(-0.5);
		case 3:
			return new BigDecimal(0);
		case 4:
			return new BigDecimal(0.5);
		case 5:
			return new BigDecimal(1);
		default:
			return new BigDecimal(0);
		}
	}

	/**
	 * 队长等级转换 按规则
	 * 
	 * @param score
	 * @return
	 */
	public static int scoreConvert(BigDecimal score) {
		if (score.doubleValue() >= -1 && score.doubleValue() < 2) {
			return 1;// 初级
		} else if (score.doubleValue() >= 2 && score.doubleValue() < 5) {
			return 2;// 中级
		} else if (score.doubleValue() >= 5 && score.doubleValue() < 10) {
			return 3;// 高级
		} else if (score.doubleValue() > 10) {
			return 4;// 特级
		}
		return 1;
	}

	/**
	 * 能力图计算
	 * 
	 * @param original
	 *            累计能力值
	 * @param newValue
	 *            当前评分
	 * @return
	 */
	public static BigDecimal abilityConvert(BigDecimal original, BigDecimal newValue) {
		BigDecimal bigDecimal = new BigDecimal(0);
		if (newValue.doubleValue() >= 50) {
			bigDecimal = BigDecimalUtil.add(original, BigDecimalUtil.divide(newValue, new BigDecimal(100)));
		}
		if (newValue.doubleValue() < 50) {
			bigDecimal = BigDecimalUtil.sub(original,
					BigDecimalUtil.divide(BigDecimalUtil.sub(new BigDecimal(50), newValue), new BigDecimal(10)));
		}
		return bigDecimal;
	}

	

	
	public static String createTelCode() {
		Random rand = new Random();// 生成随机数
		String cardNnumer = "";
		for (int a = 0; a < 4; a++) {
			cardNnumer += rand.nextInt(10);// 生成6位数字
		}
		return cardNnumer;
	}

	/**
	 * 生成32位md5码
	 * 
	 * @param password
	 * @return
	 */
	public static String md5Password(String password) {

		try {
			// 得到一个信息摘要器
			MessageDigest digest = MessageDigest.getInstance("md5");
			byte[] result = digest.digest(password.getBytes());
			StringBuffer buffer = new StringBuffer();
			// 把每一个byte 做一个与运算 0xff;
			for (byte b : result) {
				// 与运算
				int number = b & 0xff;// 加盐
				String str = Integer.toHexString(number);
				if (str.length() == 1) {
					buffer.append("0");
				}
				buffer.append(str);
			}

			// 标准的md5加密后的结果
			return buffer.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return "";
		}

	}

	public static long getMin(Date date, String time) throws ParseException {
		SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date end = dfs.parse(time);
		long between = (date.getTime() - end.getTime()) / 1000;// 除以1000是为了转换成秒
		long min = between / 60;
		return min;
	}

	public static boolean checkPassword(String password) {

		String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$";
		return password.matches(regex);
	}

	public static boolean isImage(InputStream input) {
		boolean flag = false;
		try {
			ImageInputStream is = ImageIO.createImageInputStream(input);
			if (null == is) {
				return flag;
			}
			is.close();
			flag = true;
		} catch (Exception e) {
			// e.printStackTrace();
		}
		return flag;
	}

	public static boolean isImage(File input) {
		boolean flag = false;
		try {
			ImageInputStream is = ImageIO.createImageInputStream(input);
			if (null == is) {
				return flag;
			}
			is.close();
			flag = true;
		} catch (Exception e) {
			// e.printStackTrace();
		}
		return flag;
	}

	public static void moveTotherFolders(String startPath, String endPath) {

		try {
			File startFile = new File(startPath);
			File tmpFile = new File(endPath);// 获取文件夹路径
			if (!tmpFile.exists()) {// 判断文件夹是否创建，没有创建则创建新文件夹
				tmpFile.mkdirs();
			}
			startFile.renameTo(new File(endPath + startFile.getName()));
		} catch (Exception e) {

		}
	}



	

	public static String getOrderId() {

		SimpleDateFormat simpleDateFormat;

		simpleDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");

		Date date = new Date();

		String str = simpleDateFormat.format(date);

		Random random = new Random();

		int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;// 获取5位随机数
		return rannum + str;// 当前时间
	}

	public static int countProjectLevelByScore(double levelScore) {
		if (levelScore >= 10) {
			return 5;
		} else if (levelScore < 10 && levelScore >= 8) {
			return 4;
		} else if (levelScore < 8 && levelScore >= 6) {
			return 3;
		} else if (levelScore < 6 && levelScore >= 4) {
			return 2;
		}
		return 1;
	}
}
